﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Audio;

namespace BandStandTrumpet
{
    /// <summary>
    /// Implements IServiceProvider for the application. This type is exposed through the App.Services
    /// property and can be used for ContentManagers or other types that need access to an IServiceProvider.
    /// </summary>
    public class AppServiceProvider : IServiceProvider
    {
        // A map of service type to the services themselves
        private readonly Dictionary<Type, object> services = new Dictionary<Type, object>();

        /// <summary>
        /// Adds a new service to the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to add.</param>
        /// <param name="service">The service object itself.</param>
        public void AddService(Type serviceType, object service)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");
            if (service == null)
                throw new ArgumentNullException("service");
            if (!serviceType.IsAssignableFrom(service.GetType()))
                throw new ArgumentException("service does not match the specified serviceType");

            // Add the service to the dictionary
            services.Add(serviceType, service);
        }

        /// <summary>
        /// Gets a service from the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to retrieve.</param>
        /// <returns>The service object registered for the specified type..</returns>
        public object GetService(Type serviceType)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            // Retrieve the service from the dictionary
            return services[serviceType];
        }

        /// <summary>
        /// Removes a service from the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to remove.</param>
        public void RemoveService(Type serviceType)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            // Remove the service from the dictionary
            services.Remove(serviceType);
        }
    }

    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        Texture2D[] images;
        Rectangle[] zones;
        float[] pitches;

        UIElementRenderer elementRenderer;

        SoundEffect tc;
        SoundEffectInstance inst;

        float halfstep = 1.0f / 12.0f;

        int currentNote;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as BandStand.App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
        }

        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            images = new Texture2D[5];
            images[0] = contentManager.Load<Texture2D>("trumpet");
            images[1] = contentManager.Load<Texture2D>("trumpet1down");
            images[2] = contentManager.Load<Texture2D>("trumpet2down");
            images[3] = contentManager.Load<Texture2D>("trumpet3down");
            images[4] = contentManager.Load<Texture2D>("trumpet");

            zones = new Rectangle[5];
            zones[0] = new Rectangle(332, 359, 141, 388);
            zones[1] = new Rectangle(137, 636, 60, 116);
            zones[2] = new Rectangle(137, 488, 60, 116);
            zones[3] = new Rectangle(137, 335, 60, 116);
            zones[4] = new Rectangle(39, 26, 446, 212);

            pitches = new float[5];
            pitches[0] = halfstep * 0;
            pitches[1] = halfstep * 2;
            pitches[2] = halfstep * 4;
            pitches[3] = halfstep * 7;
            pitches[4] = halfstep * 9;

            tc = contentManager.Load<SoundEffect>("Trumpet_C5_Loop");
            inst = tc.CreateInstance();

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        TimeSpan playTimeLeft;

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            currentNote = -1;
            foreach (TouchLocation t in TouchPanel.GetState())
            {
                for (int c = 0; c < zones.Length; c++)
                {
                    if (zones[c].Contains(new Microsoft.Xna.Framework.Point((int)t.Position.X, (int)t.Position.Y)))
                        currentNote = c;
                }
            }

            if (currentNote >= 0) inst.Pitch = pitches[currentNote];
            if (currentNote >= 0 && inst.State != SoundState.Playing)
            {
                inst.Play();
            }
            if (currentNote < 0) inst.Stop();
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.Draw(
                images[(int)Math.Max(0, currentNote)],
                Vector2.Zero,
                Color.White);
            elementRenderer.Render();
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();
        }
    }
}